package cn.readjava.controller;

import cn.readjava.bean.Article;
import cn.readjava.bean.ArticleCategory;
import cn.readjava.service.ArticleCategoryService;
import cn.readjava.service.ArticleService;
import cn.readjava.vo.ArticleVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ArticleController {

    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleCategoryService articleCategoryService;

    // 首页
    @GetMapping(value = {"", "/", "/index"})
    public String index(Model model) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        List<ArticleCategory> articleCategoryList = articleCategoryService.findAll();
        for (ArticleCategory temp : articleCategoryList) {
            ArticleVo articleVo = new ArticleVo();
            if (temp.getAcState() == 0) {
                articleVo.setArticleCategory(temp);
                List<Article> articles = new ArrayList<>();
                List<Article> articleList = articleService.findAllByArticleTypeId(temp.getAcId());
                for (Article article : articleList ) {
                    if (article.getArticleState() == 0) {
                        articles.add(article);
                    }
                }
                articleVo.setArticleList(articles);
                articleVoList.add(articleVo);
            }
        }
        // request.getSession().setAttribute("articleVoList", articleVoList);
        model.addAttribute("articleVoList", articleVoList);
        return "index";
    }

    // 文章详情
    @GetMapping("/article/detail/{id}")
    public String getArticle(@PathVariable Long id, Model model) {
        Article article = articleService.getOne(id);
        model.addAttribute("article", article);
        return "article-detail";
    }
}
